<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="事件名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="事件类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择事件类型" clearable>
            <el-option
              v-for="dict in eventTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          新增
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="lifeEventTableData"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column label="事件名称" prop="name" min-width="120" />
        <el-table-column label="事件类型" align="center" width="100">
          <template #default="scope">
            <el-tag 
              :type="getEventTypeTag(scope.row.type)"
            >
              {{ getEventTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="事件日期" prop="eventDate" width="120" />
        <el-table-column label="事件地点" prop="location" min-width="150" />
        <el-table-column label="相关人物" prop="personName" min-width="120" />
        <el-table-column label="创建时间" prop="createTime" width="160" />
        <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="lifeEventFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="事件名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入事件名称" />
        </el-form-item>

        <el-form-item label="事件类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择事件类型">
            <el-option
              v-for="dict in eventTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="事件日期" prop="eventDate">
          <el-date-picker
            v-model="formData.eventDate"
            type="date"
            placeholder="请选择事件日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="事件地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入事件地点" />
        </el-form-item>

        <el-form-item label="相关人物" prop="personId">
          <el-select
            v-model="formData.personId"
            placeholder="请选择相关人物"
            filterable
            @change="handlePersonChange"
          >
            <el-option
              v-for="item in personOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入事件描述"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="事件照片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleFileChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="previewVisible" width="800px">
            <img w-full :src="previewUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";
import { Plus } from '@element-plus/icons-vue';

defineOptions({
  name: "LifeEvent",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const lifeEventFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增事件",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

// 事件类型选项
const eventTypeOptions = ref([
  { value: 1, label: "出生" },
  { value: 2, label: "婚姻" },
  { value: 3, label: "逝世" },
  { value: 4, label: "迁居" },
  { value: 5, label: "入学" },
  { value: 6, label: "毕业" },
  { value: 7, label: "工作" },
  { value: 8, label: "其他" }
]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  type: undefined,
});

// 日期范围
const dateRange = ref([]);

// 分页总数
const total = ref(0);

// 事件表格数据
const lifeEventTableData = ref([]);

// 人物选项
const personOptions = ref([]);

// 选中的行ID
const selectedEventId = ref();

// 文件上传相关
const fileList = ref([]);
const previewUrl = ref('');
const previewVisible = ref(false);

// 初始表单数据
const initialFormData = ref({
  id: undefined,
  name: "",
  type: undefined,
  eventDate: "",
  location: "",
  personId: undefined,
  personName: "",
  description: "",
  mediaIds: []
});

// 表单数据
const formData = ref({ ...initialFormData.value });

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入事件名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择事件类型", trigger: "change" }],
  eventDate: [{ required: true, message: "请选择事件日期", trigger: "change" }],
  personId: [{ required: true, message: "请选择相关人物", trigger: "change" }],
});

// 获取事件类型名称
function getEventTypeName(type) {
  const found = eventTypeOptions.value.find(item => item.value === type);
  return found ? found.label : '未知';
}

// 获取事件类型标签样式
function getEventTypeTag(type) {
  const typeMap = {
    1: "success",   // 出生
    2: "warning",   // 婚姻
    3: "danger",    // 逝世
    4: "info",      // 迁居
    5: "primary",   // 入学
    6: "success",   // 毕业
    7: "warning",   // 工作
    8: "",          // 其他
  };
  return typeMap[type] || "";
}

// 查询事件列表
function handleQuery() {
  loading.value = true;
  // 处理日期范围
  const params = { ...queryParams };
  if (dateRange.value && dateRange.value.length === 2) {
    params.beginDate = dateRange.value[0];
    params.endDate = dateRange.value[1];
  }
  
  // 假设这里有一个 API 调用
  // LifeEventAPI.getList(params)
  //   .then((res) => {
  //     lifeEventTableData.value = res.data;
  //     total.value = res.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
  
  // 模拟数据
  setTimeout(() => {
    lifeEventTableData.value = [
      {
        id: "1",
        name: "张三出生",
        type: 1,
        eventDate: "1980-01-15",
        location: "北京市海淀区",
        personId: "1",
        personName: "张三",
        description: "张三在北京出生",
        createTime: "2023-01-01 12:00:00"
      },
      {
        id: "2",
        name: "李四婚礼",
        type: 2,
        eventDate: "2005-05-20",
        location: "上海市徐汇区",
        personId: "2",
        personName: "李四",
        description: "李四与王五在上海举行婚礼",
        createTime: "2023-01-02 12:00:00"
      },
      {
        id: "3",
        name: "王老先生去世",
        type: 3,
        eventDate: "2010-10-10",
        location: "广州市天河区",
        personId: "3",
        personName: "王老先生",
        description: "王老先生因病去世",
        createTime: "2023-01-03 12:00:00"
      }
    ];
    total.value = 3;
    loading.value = false;
  }, 500);
}

// 获取人物列表
function getPersonOptions() {
  // PersonAPI.getOptions()
  //   .then((data) => {
  //     personOptions.value = data;
  //   });
  
  // 模拟数据
  personOptions.value = [
    { id: "1", name: "张三" },
    { id: "2", name: "李四" },
    { id: "3", name: "王老先生" },
    { id: "4", name: "赵六" }
  ];
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  dateRange.value = [];
  queryParams.pageNum = 1;
  handleQuery();
}

// 处理每页条数变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  handleQuery();
}

// 处理页码变化
function handleCurrentChange(page) {
  queryParams.pageNum = page;
  handleQuery();
}

// 行点击事件
function handleRowClick(row) {
  selectedEventId.value = row.id;
}

// 人物选择变化
function handlePersonChange(personId) {
  const selected = personOptions.value.find(item => item.id === personId);
  if (selected) {
    formData.value.personName = selected.name;
  }
}

// 打开表单弹窗
function handleOpenDialog(id) {
  getPersonOptions();
  
  if (id) {
    dialog.title = "编辑事件";
    // LifeEventAPI.getFormData(id).then((data) => {
    //   initialFormData.value = { ...data };
    //   formData.value = data;
    //   // 加载图片列表
    //   loadMediaFiles(id);
    // });
    
    // 模拟获取数据
    const found = lifeEventTableData.value.find(item => item.id === id);
    if (found) {
      initialFormData.value = { ...found };
      formData.value = { ...found };
      
      // 模拟加载图片
      fileList.value = [
        {
          name: '示例照片.jpg',
          url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
        }
      ];
    }
  } else {
    dialog.title = "新增事件";
    resetForm();
    fileList.value = [];
  }
  dialog.visible = true;
}

// 加载媒体文件
function loadMediaFiles(eventId) {
  // MediaAPI.getByEventId(eventId).then((data) => {
  //   fileList.value = data.map(item => ({
  //     name: item.originalName,
  //     url: item.url,
  //     uid: item.id
  //   }));
  // });
}

// 图片预览
function handlePictureCardPreview(file) {
  previewUrl.value = file.url;
  previewVisible.value = true;
}

// 删除图片
function handleRemove(file) {
  fileList.value = fileList.value.filter(item => item.uid !== file.uid);
}

// 文件变更
function handleFileChange(file) {
  if (file.status === 'ready') {
    fileList.value.push(file);
  }
}

// 提交表单
function handleSubmit() {
  lifeEventFormRef.value.validate((isValid) => {
    if (isValid) {
      const id = formData.value.id;
      
      // 处理文件上传
      const formDataWithFiles = { ...formData.value };
      // formDataWithFiles.files = fileList.value.map(file => file.raw).filter(Boolean);
      
      if (id) {
        // LifeEventAPI.update(id, formDataWithFiles).then(() => {
        //   ElMessage.success("修改成功");
        //   handleCloseDialog();
        //   handleQuery();
        // });
        
        // 模拟更新
        ElMessage.success("修改成功");
        handleCloseDialog();
        handleQuery();
      } else {
        // LifeEventAPI.create(formDataWithFiles).then(() => {
        //   ElMessage.success("新增成功");
        //   handleCloseDialog();
        //   handleQuery();
        // });
        
        // 模拟新增
        ElMessage.success("新增成功");
        handleCloseDialog();
        handleQuery();
      }
    }
  });
}

// 删除事件
function handleDelete(id) {
  if (!id) {
    ElMessage.warning("请选择要删除的事件");
    return;
  }

  ElMessageBox.confirm("确认删除该事件吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      // LifeEventAPI.deleteById(id)
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     handleQuery();
      //   })
      //   .finally(() => {
      //     loading.value = false;
      //   });
      
      // 模拟删除
      setTimeout(() => {
        ElMessage.success("删除成功");
        handleQuery();
        loading.value = false;
      }, 500);
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  if (lifeEventFormRef.value) {
    lifeEventFormRef.value.resetFields();
    lifeEventFormRef.value.clearValidate();
  }
  formData.value = {
    id: undefined,
    name: "",
    type: undefined,
    eventDate: "",
    location: "",
    personId: undefined,
    personName: "",
    description: "",
    mediaIds: []
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
